package dk.simonvogensen.itodo.server.dao;

import com.google.appengine.api.datastore.Text;
import dk.simonvogensen.itodo.server.model.PersistedTodoItem;
import dk.simonvogensen.itodo.shared.model.TodoItem;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: simon
 * Date: Oct 18, 2009
 * Time: 1:04:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class PersistedTodoItemDAO {

    @SuppressWarnings("unchecked")
    public List<PersistedTodoItem> listByEmail(String email, int startIndex, long endIndex, PersistenceManager pm) {
        Query q = pm.newQuery(PersistedTodoItem.class, "email == email_address");
        q.declareParameters("java.lang.String email_address");
        q.setOrdering("index desc");
        q.setRange(startIndex, endIndex);
        List<PersistedTodoItem> persistedTodoItems = (List<PersistedTodoItem>) q.execute(email);
        return persistedTodoItems;
    }

    @SuppressWarnings("unchecked")
    public PersistedTodoItem getByLatest(String email, PersistenceManager pm) {
        Query q = pm.newQuery(PersistedTodoItem.class, "email == email_address");
        q.declareParameters("java.lang.String email_address");
        q.setOrdering("index desc");
        q.setRange(0, 1);
        List<PersistedTodoItem> persistedTodoItems = (List<PersistedTodoItem>) q.execute(email);
        if (persistedTodoItems.isEmpty()) return null;
        else return persistedTodoItems.get(0);
    }

    public PersistedTodoItem getByIndex(String email, int index, PersistenceManager pm) {
        Query q = pm.newQuery(PersistedTodoItem.class, "email == _email && index == _index");
        q.declareParameters("java.lang.String _email, java.lang.Integer _index");
        List<PersistedTodoItem> persistedTodoItems = (List<PersistedTodoItem>) q.execute(email, index);
        if (persistedTodoItems.isEmpty()) return null;
        else return persistedTodoItems.get(0);
    }

    public void delete(String id, String email, PersistenceManager pm) {
        List<PersistedTodoItem> todoItems = listByEmail(email, 0,  Long.MAX_VALUE, pm);

        // AppEngine datastore does not allow multiple conditional operators. So
        // we need to select all todoItems for this user and then do our own hash
        // join.
        for (int i = 0; i < todoItems.size(); i++) {
            PersistedTodoItem ti = todoItems.get(i);
            if (ti.getId().equals(id)) {
                pm.deletePersistent(ti);
                break;
            }
        }
    }

    public String create(TodoItem todoItem, PersistenceManager pm) {
        PersistedTodoItem persistedTodoItem = new PersistedTodoItem(todoItem);
        pm.makePersistent(persistedTodoItem);
        return persistedTodoItem.getId();
    }

    public String update(TodoItem todoItem, PersistenceManager pm) {
        String id = null;
        Transaction tx = pm.currentTransaction();
        try {
            tx.begin();
            PersistedTodoItem managedTodoItem = pm.getObjectById(PersistedTodoItem.class, todoItem.getId());
            if (managedTodoItem != null) {
                managedTodoItem.setEmail(todoItem.getEmail());
                managedTodoItem.setIndex(todoItem.getIndex());
                managedTodoItem.setText(new Text(todoItem.getText()));
                id = managedTodoItem.getId();
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (tx.isActive()) {
                tx.rollback();
            }
        }
        return id;
    }
}
